//
// C++ Implementation: applicationinfo
//
// Description:
//
//
// Author: Ernesto Barragan <ernestus *at* gmail.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "applicationinfo.h"
#include <QFile>
#include <QTextStream>

ApplicationInfo::ApplicationInfo( const ApplicationInfo& rhs )
{
    m_name = rhs.name() ;
    m_execString = rhs.execString() ;
    m_comment = rhs.comment() ;
    m_icon = rhs.icon() ;
}

ApplicationInfo::ApplicationInfo( const QString& filePath )
{
    bool desktopEntry = false ;
    bool applicationDesktopEntry = false ;
    QFile desktopFile( filePath ) ;
    if (false == desktopFile.open( QIODevice::ReadOnly | QIODevice::Text ))
    {
        return;
    }
    QTextStream text(&desktopFile);


    ///@fixme this is a very weak parser, accepts almost everything...
    while (false == text.atEnd())
    {
        QString line = text.readLine().trimmed() ;
        if ( true == line.startsWith("[Desktop Entry]", Qt::CaseInsensitive ) )
        {
            desktopEntry = true ;
        }
        else if ( true == line.startsWith("Name", Qt::CaseInsensitive ) )
        {
            m_name = m_rightValue( line ) ;
        }
        else if ( true == line.startsWith("Exec", Qt::CaseInsensitive ) )
        {
            m_execString = m_rightValue( line ) ;
        }
        else if( line.startsWith("Comment", Qt::CaseInsensitive ) )
        {
            m_comment = m_rightValue( line ) ;
        }
        else if( line.startsWith("Icon", Qt::CaseInsensitive ) )
        {
            m_icon = m_rightValue( line ) ;
        }
        else if ( true == line.startsWith("Type", Qt::CaseInsensitive ) )
        {
            QString rval = m_rightValue( line ) ;
            applicationDesktopEntry = rval.startsWith( "Application", Qt::CaseInsensitive ) ;
        }
    }
}

ApplicationInfo::~ApplicationInfo()
{

}

QString ApplicationInfo::execString() const
{
    return m_execString ;
}

QString ApplicationInfo::name() const
{
    return m_name ;
}

QString ApplicationInfo::comment() const
{
    return m_comment ;
}

QString ApplicationInfo::icon() const
{
    return m_icon ;
}

bool ApplicationInfo::isValid() const
{
    return (false == m_execString.isEmpty()) ;
}

QString ApplicationInfo::m_rightValue( const QString& expr ) const
{
    QString result ;
    int equalIsAtPos = expr.indexOf('=') ;

    if( 0 > equalIsAtPos )
    {
        return result ; //no '=' found, return empty string
    }

    result = expr.mid( equalIsAtPos+1 ).trimmed() ;
    return result ;
}
